<template>
  <div class="reminder-view">
    <div class="page-header">
      <h2>提醒管理</h2>
      <p>管理您的穿搭提醒和购物清单</p>
    </div>

    <!-- 操作栏 -->
    <el-card class="action-bar">
      <el-row :gutter="20" justify="space-between">
        <el-col :span="12">
          <el-button-group>
            <el-button 
              :type="activeTab === 'all' ? 'primary' : ''"
              @click="setActiveTab('all')"
            >
              全部提醒
            </el-button>
            <el-button 
              :type="activeTab === 'today' ? 'primary' : ''"
              @click="setActiveTab('today')"
            >
              今日提醒
            </el-button>
            <el-button 
              :type="activeTab === 'pending' ? 'primary' : ''"
              @click="setActiveTab('pending')"
            >
              待处理
            </el-button>
            <el-button 
              :type="activeTab === 'completed' ? 'primary' : ''"
              @click="setActiveTab('completed')"
            >
              已完成
            </el-button>
          </el-button-group>
        </el-col>
        <el-col :span="12" style="text-align: right;">
          <el-dropdown @command="handleCreateReminder">
            <el-button type="primary">
              <el-icon><Plus /></el-icon>
              创建提醒
              <el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="laundry">洗涤提醒</el-dropdown-item>
                <el-dropdown-item command="seasonal">换季提醒</el-dropdown-item>
                <el-dropdown-item command="shopping">购物提醒</el-dropdown-item>
                <el-dropdown-item command="custom">自定义提醒</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-col>
      </el-row>
    </el-card>

    <!-- 今日提醒概览 -->
    <el-card v-if="activeTab === 'today' || activeTab === 'all'" class="today-reminders">
      <template #header>
        <div class="card-header">
          <span>今日提醒</span>
          <el-tag :type="todayReminders.length > 0 ? 'warning' : 'success'">
            {{ todayReminders.length }} 个
          </el-tag>
        </div>
      </template>

      <div v-if="todayReminders.length === 0" class="empty-state">
        <el-empty description="今天没有提醒事项" />
      </div>

      <div v-else class="reminder-list">
        <div 
          v-for="reminder in todayReminders" 
          :key="reminder.id"
          class="reminder-item today-item"
        >
          <div class="reminder-content">
            <div class="reminder-icon">
              <el-icon v-if="reminder.type === 'laundry'"><Brush /></el-icon>
              <el-icon v-else-if="reminder.type === 'seasonal'"><Calendar /></el-icon>
              <el-icon v-else-if="reminder.type === 'shopping'"><ShoppingBag /></el-icon>
              <el-icon v-else><Bell /></el-icon>
            </div>
            
            <div class="reminder-info">
              <h4>{{ reminder.title }}</h4>
              <p>{{ reminder.description }}</p>
              <div class="reminder-meta">
                <el-tag :type="getPriorityType(reminder.priority)" size="small">
                  {{ getPriorityText(reminder.priority) }}
                </el-tag>
                <span class="reminder-time">
                  {{ formatTime(reminder.reminder_date) }}
                </span>
              </div>
            </div>
          </div>
          
          <div class="reminder-actions">
            <el-button 
              size="small" 
              type="success" 
              @click="completeReminder(reminder.id)"
            >
              完成
            </el-button>
            <el-button 
              size="small" 
              @click="editReminder(reminder)"
            >
              编辑
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 提醒列表 -->
    <el-card class="reminder-list-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>提醒列表</span>
          <div class="filter-controls">
            <el-select v-model="filterType" placeholder="类型筛选" style="width: 120px;" @change="loadReminders">
              <el-option label="全部" value="" />
              <el-option label="洗涤" value="laundry" />
              <el-option label="换季" value="seasonal" />
              <el-option label="购物" value="shopping" />
              <el-option label="自定义" value="custom" />
            </el-select>
          </div>
        </div>
      </template>

      <div v-if="reminders.length === 0" class="empty-state">
        <el-empty description="暂无提醒" />
      </div>

      <div v-else class="reminder-list">
        <div 
          v-for="reminder in reminders" 
          :key="reminder.id"
          class="reminder-item"
          :class="{ 
            completed: reminder.is_completed,
            overdue: isOverdue(reminder.reminder_date) && !reminder.is_completed
          }"
        >
          <div class="reminder-content">
            <div class="reminder-icon">
              <el-icon v-if="reminder.type === 'laundry'"><Brush /></el-icon>
              <el-icon v-else-if="reminder.type === 'seasonal'"><Calendar /></el-icon>
              <el-icon v-else-if="reminder.type === 'shopping'"><ShoppingBag /></el-icon>
              <el-icon v-else><Bell /></el-icon>
            </div>
            
            <div class="reminder-info">
              <h4>{{ reminder.title }}</h4>
              <p>{{ reminder.description }}</p>
              <div class="reminder-meta">
                <el-tag :type="getTypeColor(reminder.type)" size="small">
                  {{ getTypeText(reminder.type) }}
                </el-tag>
                <el-tag :type="getPriorityType(reminder.priority)" size="small">
                  {{ getPriorityText(reminder.priority) }}
                </el-tag>
                <span class="reminder-date">
                  {{ formatDate(reminder.reminder_date) }}
                </span>
                <span v-if="reminder.repeat_type !== 'none'" class="repeat-info">
                  <el-icon><Refresh /></el-icon>
                  {{ getRepeatText(reminder.repeat_type) }}
                </span>
              </div>
            </div>
          </div>
          
          <div class="reminder-actions">
            <el-button 
              v-if="!reminder.is_completed"
              size="small" 
              type="success" 
              @click="completeReminder(reminder.id)"
            >
              完成
            </el-button>
            <el-button 
              size="small" 
              @click="editReminder(reminder)"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteReminder(reminder.id)"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑提醒对话框 -->
    <el-dialog 
      v-model="reminderDialogVisible" 
      :title="isEditMode ? '编辑提醒' : '创建提醒'"
      width="600px"
    >
      <el-form :model="reminderForm" :rules="reminderRules" ref="reminderFormRef" label-width="100px">
        <el-form-item label="提醒类型" prop="type">
          <el-select v-model="reminderForm.type" placeholder="选择类型">
            <el-option label="洗涤提醒" value="laundry" />
            <el-option label="换季提醒" value="seasonal" />
            <el-option label="购物提醒" value="shopping" />
            <el-option label="自定义提醒" value="custom" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="标题" prop="title">
          <el-input v-model="reminderForm.title" placeholder="请输入提醒标题" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="reminderForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入提醒描述"
          />
        </el-form-item>
        
        <el-form-item label="提醒时间" prop="reminder_date">
          <el-date-picker
            v-model="reminderForm.reminder_date"
            type="datetime"
            placeholder="选择提醒时间"
            style="width: 100%;"
          />
        </el-form-item>
        
        <el-form-item label="重复类型" prop="repeat_type">
          <el-select v-model="reminderForm.repeat_type" placeholder="选择重复类型">
            <el-option label="不重复" value="none" />
            <el-option label="每天" value="daily" />
            <el-option label="每周" value="weekly" />
            <el-option label="每月" value="monthly" />
            <el-option label="每年" value="yearly" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="reminderForm.priority" placeholder="选择优先级">
            <el-option label="低" value="low" />
            <el-option label="中" value="medium" />
            <el-option label="高" value="high" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="reminderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveReminder" :loading="saving">
          {{ isEditMode ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reminderAPI } from '@/api'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const activeTab = ref('all')
const filterType = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

const reminders = ref([])
const todayReminders = ref([])
const reminderDialogVisible = ref(false)
const isEditMode = ref(false)
const editingReminderId = ref(null)

// 表单数据
const reminderForm = reactive({
  type: '',
  title: '',
  description: '',
  reminder_date: '',
  repeat_type: 'none',
  priority: 'medium'
})

// 表单验证规则
const reminderRules = {
  type: [{ required: true, message: '请选择提醒类型', trigger: 'change' }],
  title: [{ required: true, message: '请输入提醒标题', trigger: 'blur' }],
  reminder_date: [{ required: true, message: '请选择提醒时间', trigger: 'change' }]
}

const reminderFormRef = ref()

// 计算属性
const filteredReminders = computed(() => {
  let filtered = reminders.value
  
  if (activeTab.value === 'pending') {
    filtered = filtered.filter(r => !r.is_completed && r.is_active)
  } else if (activeTab.value === 'completed') {
    filtered = filtered.filter(r => r.is_completed)
  }
  
  return filtered
})

// 方法
const setActiveTab = (tab) => {
  activeTab.value = tab
  currentPage.value = 1
  if (tab === 'today') {
    loadTodayReminders()
  } else {
    loadReminders()
  }
}

const loadReminders = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      type: filterType.value
    }
    
    if (activeTab.value === 'pending') {
      params.status = 'pending'
    } else if (activeTab.value === 'completed') {
      params.status = 'completed'
    }
    
    const response = await reminderAPI.getList(params)
    
    if (response.code === 200) {
      reminders.value = response.data.list || []
      total.value = response.data.total || 0
    } else {
      throw new Error(response.message || '获取提醒列表失败')
    }
  } catch (error) {
    console.error('获取提醒列表失败:', error)
    ElMessage.error('获取提醒列表失败')
  } finally {
    loading.value = false
  }
}

const loadTodayReminders = async () => {
  try {
    const response = await reminderAPI.getTodayReminders()
    
    if (response.code === 200) {
      todayReminders.value = response.data || []
    } else {
      throw new Error(response.message || '获取今日提醒失败')
    }
  } catch (error) {
    console.error('获取今日提醒失败:', error)
    ElMessage.error('获取今日提醒失败')
  }
}

const handleCreateReminder = (type) => {
  isEditMode.value = false
  editingReminderId.value = null
  
  // 重置表单
  Object.assign(reminderForm, {
    type,
    title: '',
    description: '',
    reminder_date: '',
    repeat_type: 'none',
    priority: 'medium'
  })
  
  // 根据类型设置默认值
  if (type === 'laundry') {
    reminderForm.title = '洗涤提醒'
    reminderForm.description = '该洗涤衣物了'
  } else if (type === 'seasonal') {
    reminderForm.title = '换季提醒'
    reminderForm.description = '该整理换季衣物了'
  } else if (type === 'shopping') {
    reminderForm.title = '购物提醒'
    reminderForm.description = '查看购物清单'
  }
  
  reminderDialogVisible.value = true
}

const editReminder = (reminder) => {
  isEditMode.value = true
  editingReminderId.value = reminder.id
  
  Object.assign(reminderForm, {
    type: reminder.type,
    title: reminder.title,
    description: reminder.description,
    reminder_date: new Date(reminder.reminder_date),
    repeat_type: reminder.repeat_type,
    priority: reminder.priority
  })
  
  reminderDialogVisible.value = true
}

const saveReminder = async () => {
  try {
    await reminderFormRef.value.validate()
    saving.value = true
    
    const data = { ...reminderForm }
    
    if (isEditMode.value) {
      await reminderAPI.update(editingReminderId.value, data)
      ElMessage.success('提醒更新成功')
    } else {
      await reminderAPI.create(data)
      ElMessage.success('提醒创建成功')
    }
    
    reminderDialogVisible.value = false
    loadReminders()
    if (activeTab.value === 'today' || activeTab.value === 'all') {
      loadTodayReminders()
    }
  } catch (error) {
    console.error('保存提醒失败:', error)
    ElMessage.error('保存提醒失败')
  } finally {
    saving.value = false
  }
}

const completeReminder = async (id) => {
  try {
    await reminderAPI.markAsCompleted(id)
    ElMessage.success('提醒已完成')
    loadReminders()
    loadTodayReminders()
  } catch (error) {
    console.error('完成提醒失败:', error)
    ElMessage.error('完成提醒失败')
  }
}

const deleteReminder = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个提醒吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await reminderAPI.delete(id)
    ElMessage.success('提醒删除成功')
    loadReminders()
    loadTodayReminders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除提醒失败:', error)
      ElMessage.error('删除提醒失败')
    }
  }
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadReminders()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadReminders()
}

// 辅助方法
const isOverdue = (date) => {
  return new Date(date) < new Date()
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

const formatTime = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

const getTypeColor = (type) => {
  const colors = {
    laundry: 'primary',
    seasonal: 'success',
    shopping: 'warning',
    custom: 'info'
  }
  return colors[type] || 'info'
}

const getTypeText = (type) => {
  const texts = {
    laundry: '洗涤',
    seasonal: '换季',
    shopping: '购物',
    custom: '自定义'
  }
  return texts[type] || '未知'
}

const getPriorityType = (priority) => {
  const types = {
    low: 'info',
    medium: 'warning',
    high: 'danger'
  }
  return types[priority] || 'info'
}

const getPriorityText = (priority) => {
  const texts = {
    low: '低',
    medium: '中',
    high: '高'
  }
  return texts[priority] || '中'
}

const getRepeatText = (repeatType) => {
  const texts = {
    none: '不重复',
    daily: '每天',
    weekly: '每周',
    monthly: '每月',
    yearly: '每年'
  }
  return texts[repeatType] || '不重复'
}

// 页面初始化
onMounted(() => {
  loadReminders()
  loadTodayReminders()
})
</script>

<style scoped>
.reminder-view {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.action-bar,
.today-reminders,
.reminder-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

.reminder-list {
  space-y: 12px;
}

.reminder-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border: 1px solid #eee;
  border-radius: 8px;
  margin-bottom: 12px;
  transition: all 0.3s;
}

.reminder-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.reminder-item.today-item {
  border-color: #409EFF;
  background: #f0f9ff;
}

.reminder-item.completed {
  opacity: 0.6;
  background: #f5f5f5;
}

.reminder-item.overdue {
  border-color: #f56c6c;
  background: #fef0f0;
}

.reminder-content {
  display: flex;
  align-items: center;
  flex: 1;
}

.reminder-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 18px;
}

.reminder-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  color: #333;
}

.reminder-info p {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
}

.reminder-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.reminder-date,
.reminder-time {
  font-size: 12px;
  color: #999;
}

.repeat-info {
  display: flex;
  align-items: center;
  gap: 2px;
  font-size: 12px;
  color: #999;
}

.reminder-actions {
  display: flex;
  gap: 8px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .reminder-view {
    padding: 16px;
  }
  
  .reminder-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .reminder-content {
    width: 100%;
    margin-bottom: 12px;
  }
  
  .reminder-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .filter-controls {
    width: 100%;
  }
}
</style>
